#include "Config.h"
#include "Connector.h"

#include "TcpServer.h"

#include "Common/Stream.h"
#include <event2/buffer.h>
#include <event2/bufferevent.h>

#include "MsgHandler/MsgTypes.h"
#include "MsgHandler/MsgPool.h"

namespace Network
{

Connector::Connector( int fd, TcpSlaveServer * s, int id, const std::string& ip, UInt16 port ) :
	TcpConduit(fd, s, id), _connected(false)
{
	struct sockaddr_in addr = {0};
	addr.sin_family = AF_INET;
	addr.sin_addr.s_addr = htonl(ResolveAddress( ip.c_str() ));
	addr.sin_port = htons( port );
	if(bufferevent_socket_connect(_bev, (struct sockaddr *)&addr, sizeof(addr)) < 0)
		throw std::bad_exception();
}

Connector::~Connector()
{
}

UInt16 Connector::parsePacket( struct evbuffer * buf, int &off, int &len )
{
	size_t l = evbuffer_get_length(buf);
	if(l < 6)
	{
		off = 0;
		len = 0;
		return 0;
	}
	UInt8 * buf_ = static_cast<UInt8 *>(evbuffer_pullup(buf, 6));
	UInt32 len2 = *reinterpret_cast<UInt16 *>(buf_);
	if(len2 > l)
	{
		off = 0;
		len = 0;
		return 0;
	}

	off = 6;
	len = len2;

	return *reinterpret_cast<UInt16 *>(&buf_[4]);
}

void Connector::onRecv( UInt16 cmd, int len, void * buf )
{
	//printf("Recv CMD : %04X\n", cmd);
}

void Connector::onDisconnected()
{
	_connected = false;
	int id = fd();
	_host->lostConnection( -id );
}

void Connector::onConnected()
{
	_connected = true;
}

void Connector::send( const void * buf, int size )
{
	if(!_connected)
		return;
	TcpConduit::send(buf, size);
}

}
